/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.edu.vttu.phong;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.table.TableModel;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import vn.edu.vttu.readxml.ReadXML;
import vn.edu.vttu.readxml.thongtindb;

/**
 *
 * @author nhphuoc
 */
public class QuanLy_LoaiPhong extends javax.swing.JFrame {
    
    /**
     * Creates new form QuanLy_LoaiDichVu
     */
    private boolean them = false;

    public QuanLy_LoaiPhong() {
        initComponents();
        setLocation(480, 100);
        loadLoaiphong();
        enableButton(true);
        txtTenloai.setEnabled(false);
        txtDongia.setEnabled(false);
        int index=0;
        txtMa.setText(String.valueOf(tbloaiphong.getValueAt(index, 0)));
        txtTenloai.setText(String.valueOf(tbloaiphong.getValueAt(index, 1)));
        txtDongia.setText(String.valueOf(tbloaiphong.getValueAt(index, 2)));
    }

    private void loadLoaiphong() {
        try {
            ReadXML read = new ReadXML();
            Registry registry = LocateRegistry.getRegistry(read.getInfo("ipServer"), Integer.parseInt(read.getInfo("portserver")));
            vn.edu.vttu.RMI_Interface common = (vn.edu.vttu.RMI_Interface) registry.lookup("ServerKhachSan");
            TableModel x = common.LoadLoaiPhong();
            this.tbloaiphong.setModel(x);
            this.tbloaiphong.setRowSelectionInterval(0, 0);
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(rootPane, e);
        }
    }

    private void enableButton(boolean b) {
        buttonThem.setEnabled(b);
        buttonSua.setEnabled(b);
        buttonXoa.setEnabled(b);
        buttonLuu.setEnabled(!b);

        tbloaiphong.setEnabled(b);

    }

    private boolean testNumber(String num) {
        boolean test = false;
        if (num.equals("")) {
            test = false;
        } else {
            for (int i = 0; i < num.length(); i++) {
                if (Character.isLetter(num.charAt(i))) {
                    test = false;
                    break;
                }
                if (i + 1 == num.length()) {
                    test = true;
                }
            }
        }
        return test;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtMa = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtTenloai = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtDongia = new javax.swing.JTextField();
        buttonThem = new javax.swing.JButton();
        buttonSua = new javax.swing.JButton();
        buttonXoa = new javax.swing.JButton();
        buttonLuu = new javax.swing.JButton();
        buttonHuy = new javax.swing.JButton();
        buttonPrint = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbloaiphong = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 51, 255));
        jLabel1.setText("QUẢN LÝ LOẠI PHÒNG");

        jLabel2.setText("Mã: ");

        txtMa.setEditable(false);

        jLabel3.setText("Tên Loại");

        jLabel4.setText("Đơn Giá");

        txtDongia.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDongiaKeyTyped(evt);
            }
        });

        buttonThem.setText("Thêm");
        buttonThem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonThemActionPerformed(evt);
            }
        });

        buttonSua.setText("Sửa");
        buttonSua.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSuaActionPerformed(evt);
            }
        });

        buttonXoa.setText("Xóa");
        buttonXoa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonXoaActionPerformed(evt);
            }
        });

        buttonLuu.setText("Lưu");
        buttonLuu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLuuActionPerformed(evt);
            }
        });

        buttonHuy.setText("Hủy");
        buttonHuy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonHuyActionPerformed(evt);
            }
        });

        buttonPrint.setText("Print");
        buttonPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonPrintActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Danh sách loại phòng"));

        tbloaiphong.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tbloaiphong.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbloaiphongMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbloaiphong);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 12, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(77, 77, 77)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(103, 103, 103))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(buttonThem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonSua, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonXoa, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonLuu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonHuy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonPrint, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(41, 41, 41))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtMa, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTenloai, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDongia, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtMa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(txtTenloai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(txtDongia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonThem)
                    .addComponent(buttonSua)
                    .addComponent(buttonXoa)
                    .addComponent(buttonLuu)
                    .addComponent(buttonHuy)
                    .addComponent(buttonPrint))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonThemActionPerformed
        txtTenloai.setEnabled(true);
        txtDongia.setEnabled(true);
        txtTenloai.setText("");
        txtDongia.setText("");
        enableButton(false);
        them = true;
    }//GEN-LAST:event_buttonThemActionPerformed

    private void buttonSuaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSuaActionPerformed
        them = false;
        txtTenloai.setEnabled(true);
        txtDongia.setEnabled(true);
        enableButton(false);
    }//GEN-LAST:event_buttonSuaActionPerformed

    private void buttonLuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLuuActionPerformed
        String tenloai = "";
        int dongiadv;
        if (txtTenloai.getText().equals("") || txtDongia.getText().equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Bạn chưa nhập tên loại phòng hoặc đơn giá");
            if (txtTenloai.getText().equals("")) {
                txtTenloai.requestFocus();
            } else {
                txtDongia.requestFocus();
            }
        } else if (Integer.parseInt(txtDongia.getText().toString()) < 0) {
            JOptionPane.showMessageDialog(rootPane, "Bạn nhập đơn giá sai");
            txtDongia.requestFocus();
        } else if (testNumber(txtDongia.getText().toString()) == false) {
            JOptionPane.showMessageDialog(rootPane, "Bạn nhập đơn giá sai");
            txtDongia.requestFocus();
        } else {
            tenloai = txtTenloai.getText().trim();

            if (them == true) {
                try {
                    dongiadv = Integer.parseInt(txtDongia.getText().toString());
                    ReadXML read = new ReadXML();
                    Registry registry = LocateRegistry.getRegistry(read.getInfo("ipServer"), Integer.parseInt(read.getInfo("portserver")));
                    vn.edu.vttu.RMI_Interface common = (vn.edu.vttu.RMI_Interface) registry.lookup("ServerKhachSan");
                    boolean x = common.insertLoaiPhong(tenloai, dongiadv);
                    if (x) {
                        JOptionPane.showMessageDialog(rootPane, "Thêm loại phòng thành công");
                        loadLoaiphong();
                        enableButton(true);
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Thêm loại phòng không thành công");
                        loadLoaiphong();
                        enableButton(true);
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(rootPane, "Đã xay ra lỗi: " + ex.getMessage());
                    loadLoaiphong();
                    enableButton(true);
                    enableButton(true);
                }

            } else {
                try {
                    int id = Integer.parseInt(txtMa.getText().toString());
                    dongiadv = Integer.parseInt(txtDongia.getText().toString());
                    ReadXML read = new ReadXML();
                    Registry registry = LocateRegistry.getRegistry(read.getInfo("ipServer"), Integer.parseInt(read.getInfo("portserver")));
                    vn.edu.vttu.RMI_Interface common = (vn.edu.vttu.RMI_Interface) registry.lookup("ServerKhachSan");
                    boolean x = common.updateLoaiPhong(id, tenloai, dongiadv);
                    if (x) {
                        JOptionPane.showMessageDialog(rootPane, "Cập nhật loại phòng thành công");
                        loadLoaiphong();
                        enableButton(true);
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Cập nhật loại phòng không thành công");
                        loadLoaiphong();
                        enableButton(true);
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(rootPane, "Bạn nhập sai đơn giá");
                    txtDongia.requestFocus();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(rootPane, "Đã xay ra lỗi: " + ex.getMessage());
                    loadLoaiphong();
                    enableButton(true);
                    enableButton(true);
                }
            }
        }
    }//GEN-LAST:event_buttonLuuActionPerformed

    private void buttonXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonXoaActionPerformed
        if (txtMa.getText().equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Chưa chọn loại phòng để xóa");
        } else {
            int i = JOptionPane.showConfirmDialog(this, "Bạn có muốn xóa dữ liệu này không?", "Cảnh Báo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (i == 0) {
                try {
                    int id = Integer.parseInt(txtMa.getText().toString());
                    ReadXML read = new ReadXML();
                    Registry registry = LocateRegistry.getRegistry(read.getInfo("ipServer"), Integer.parseInt(read.getInfo("portserver")));
                    vn.edu.vttu.RMI_Interface common = (vn.edu.vttu.RMI_Interface) registry.lookup("ServerKhachSan");
                    boolean x = common.DeleteLoaiPhong(id);
                    if (x) {
                        JOptionPane.showMessageDialog(rootPane, "Xóa loại phòng thành công");
                        loadLoaiphong();
                        enableButton(true);
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Xóa loại phòng không thành công");
                        loadLoaiphong();
                        enableButton(true);
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(rootPane, "Đã xay ra lỗi: " + ex.getMessage());
                    loadLoaiphong();
                    enableButton(true);
                    enableButton(true);
                }
            }
        }
    }//GEN-LAST:event_buttonXoaActionPerformed

    private void txtDongiaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDongiaKeyTyped
        int key = evt.getKeyChar();
        String st = txtDongia.getText();
        String stTest = "0123456789";
        if (key != evt.VK_BACK_SPACE
                && key != evt.VK_DELETE
                && key != evt.VK_ENTER) {
            int flag = 0;
            if (stTest.indexOf(evt.getKeyChar()) == -1) {
                flag++;
                JOptionPane.showMessageDialog(this, "Chỉ được nhập số");
            }
            if (flag > 0) {
                evt.consume();
            }
        }
    }//GEN-LAST:event_txtDongiaKeyTyped

    private void tbloaiphongMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbloaiphongMouseClicked
        int index=tbloaiphong.getSelectedRow();
        txtMa.setText(String.valueOf(tbloaiphong.getValueAt(index, 0)));
        txtTenloai.setText(String.valueOf(tbloaiphong.getValueAt(index, 1)));
        txtDongia.setText(String.valueOf(tbloaiphong.getValueAt(index, 2)));
    }//GEN-LAST:event_tbloaiphongMouseClicked

    private void buttonHuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonHuyActionPerformed
        loadLoaiphong();
        enableButton(true);
        txtTenloai.setEnabled(false);
        txtDongia.setEnabled(false);
        int index=0;
        txtMa.setText(String.valueOf(tbloaiphong.getValueAt(index, 0)));
        txtTenloai.setText(String.valueOf(tbloaiphong.getValueAt(index, 1)));
        txtDongia.setText(String.valueOf(tbloaiphong.getValueAt(index, 2)));
    }//GEN-LAST:event_buttonHuyActionPerformed

    private void buttonPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPrintActionPerformed
        String link = "src\\vn\\edu\\vttu\\phong\\danhsachloaiphong.jrxml";
        try {
            //Tạo kết nối đến Mysql
            Class.forName("com.mysql.jdbc.Driver");
            String database = "jdbc:mysql://"+thongtindb.getIp()+":"+thongtindb.getPort()+"/"+thongtindb.getDb();
            String us = thongtindb.getU();
            String pa = thongtindb.getP();
            Map<String, Object> params = new HashMap<String, Object>();  
            Connection conn = (Connection) DriverManager.getConnection(database, us, pa);
            // tạo JasperReport
            JasperReport jr = JasperCompileManager.compileReport(link);
            //tạo JasperPrint
            JasperPrint jp = JasperFillManager.fillReport(jr, params, conn);            
            JasperViewer jv = new JasperViewer(jp, false); 
            jv.setVisible(true); 
        } catch (Exception ex) {

        }
    }//GEN-LAST:event_buttonPrintActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(QuanLy_LoaiPhong.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(QuanLy_LoaiPhong.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(QuanLy_LoaiPhong.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(QuanLy_LoaiPhong.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new QuanLy_LoaiPhong().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonHuy;
    private javax.swing.JButton buttonLuu;
    private javax.swing.JButton buttonPrint;
    private javax.swing.JButton buttonSua;
    private javax.swing.JButton buttonThem;
    private javax.swing.JButton buttonXoa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbloaiphong;
    private javax.swing.JTextField txtDongia;
    private javax.swing.JTextField txtMa;
    private javax.swing.JTextField txtTenloai;
    // End of variables declaration//GEN-END:variables
}
